package com.example.library_common.view;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.example.library_common.R;

public class ImageProgress extends FrameLayout {

    private ImageView upAvatar;

    public ImageProgress(@NonNull Context context) {
        this(context, null);
    }

    public ImageProgress(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ImageProgress(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        inflate(context,R.layout.image_progress_layout,this);
        ImageView downAvatar = findViewById(R.id.downAvatar);
        upAvatar = findViewById(R.id.upAvatar);

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ImageProgress);
        int down_color = array.getColor(R.styleable.ImageProgress_down_color, Color.WHITE);
        int up_color = array.getColor(R.styleable.ImageProgress_up_color, Color.WHITE);

        Drawable downDrawable = null;

        Drawable upDrawable = null;

        try {
            int avatar = array.getResourceId(R.styleable.ImageProgress_avatar, 0);
            downDrawable = ContextCompat.getDrawable(context, avatar);
            upDrawable = ContextCompat.getDrawable(context, avatar);
        } catch (Exception e) {
            e.printStackTrace();
        }

        array.recycle();

        if (downDrawable != null) {
            Drawable downDrawableWrap = DrawableCompat.wrap(downDrawable);
            DrawableCompat.setTint(downDrawableWrap, down_color);
            downAvatar.setImageDrawable(downDrawableWrap);
        }

        if (upDrawable != null) {
            Drawable upDrawableWrap = DrawableCompat.wrap(upDrawable);
            DrawableCompat.setTint(upDrawableWrap, up_color);
            ClipDrawable clipDrawable = new ClipDrawable(upDrawableWrap, Gravity.START, ClipDrawable.HORIZONTAL);
            upAvatar.setImageDrawable(clipDrawable);
        }
    }

    public void setProgress(float progress) {
        Drawable drawable = upAvatar.getDrawable();
        if (drawable != null) {
            int mLevel = (int) (10000 * progress);
            Log.d("setProgress", "setProgress: "+mLevel);
            drawable.setLevel(mLevel);
        }
    }

}
